<template>
  <el-dialog
      v-model="savaExcelDialig"
      title="导出用户"
      width="500"
  >
    <!--    :before-close="handleClose"-->
    <el-input v-model="excelName" style="" placeholder="请输入导出表格的名称"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="savaExcelDialig = false">取消</el-button>
        <el-button type="primary" @click="exportExcel">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-button type="primary" @click="exportData">数据导出</el-button>
  <el-table :data="tableData" border style="width: 100%;margin-top: 10px">
    <el-table-column prop="nickname" label="姓名" width="180"/>
    <el-table-column prop="email" label="邮箱" width="180"/>
    <el-table-column prop="phone" label="手机号"/>
    <el-table-column prop="idcard" label="身份证号">
      <template #default='{row}'>
        {{ (decrypt(row.idcard) === 'null' || decrypt(row.idcard) === null) ? '' : decrypt(row.idcard)}}
      </template>
    </el-table-column>
    <el-table-column prop="location" label="学校（单位）"/>
    <el-table-column prop="admin" label="角色">
      <template #default='{row}'>
        <el-tag type="danger" size="large" v-show="row.admin >1 ">超级管理员</el-tag>
        <el-tag type="warning" size="large" v-show="row.admin === 1">管理员</el-tag>
        <el-tag type="info" size="large" v-show="row.admin === 0">用户</el-tag>
      </template>
    </el-table-column>

    <el-table-column
        label='管理员设定'
        fixed='right'
        width='200'
        align='center'
    >
      <template #default='{row}'>
        <el-button
            :type="row.admin >= 1? 'danger':'success'"
            size='small'
            @click='settingClick(row)'
        >{{ row.admin >= 1 ? '取消管理员' : '设为管理员' }}
        </el-button
        >
      </template>
    </el-table-column>

    <el-table-column
        label='账户状态'
        fixed='right'
        width='200'
        align='center'
    >
      <template #default='{row}'>
        <el-button
            :type="row.logout === 1? 'success':'danger'"
            size='small'
            @click='logoutClick(row)'
        >{{ row.logout === 1 ? '正常' : '注销' }}
        </el-button
        >
      </template>
    </el-table-column>

  </el-table>

  <el-pagination
      class='pagination'
      @size-change='handleSizeChange'
      @current-change='handleCurrentChange'
      :current-page='page'
      :page-size='size'
      :page-sizes='[5, 10, 20]'
      layout='total, sizes, prev, pager, next, jumper'
      :total='total'
  >
  </el-pagination>

</template>

<script setup>

//查询出的表格数据


//listUser
import {ref, onMounted, computed, onBeforeUpdate, watch, reactive} from 'vue'
import {listUser, setA, setL, unsetA, unsetL} from "@/api/user";
import {USERS} from "@/utils/Export2ExcelContants";
import store from '@/store'
import {decrypt} from '@/utils/secret'

const tableData = ref([])
const page = ref(1) // 页数
const size = ref(10)// 页面数
const total = ref(0) // 总数
const loading = ref(false)
//显示保存 excel
const savaExcelDialig = ref(false)
const excelName = ref('用户数据表')


onMounted(() => {
  console.log('onMounted')
  listFun()
})


const listFun = async (page, pagesize) => {
  // 设置分页参数
  let res = await listUser({
    page,
    pagesize,
  })
  // console.log(res)
  tableData.value = res.msg.data
  total.value = res.msg.total
}

/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  listFun(page.value, size.value)
}

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  listFun(page.value, size.value)
}


//导出用户数据
const exportData = () => {
  console.log('导出设备数据')
  savaExcelDialig.value = true
}

const formatJson = (headers, rows) => {
  return rows.map(item => {
    return Object.keys(headers).map(key => {
      return item[headers[key]]
    })
  })
}

const exportExcel = async () => {
  console.log('导出excel')
  const result = await listUser({
    page: 1,
    pagesize: 30,
  })
  // console.log('result= ', result)
  let data = result.msg.data
  console.log('data= ', data)
  const excel = await import('@/utils/Export2Excel')
  const a = formatJson(USERS, data)
  // console.log('a=  ', a)
  excel.export_json_to_excel({
    //excel表头 ['用户ID', '上传人名字', '上传人姓氏', '邮件地址', '电话', '公司', '国家', '摘要', '文章']
    //excel数据
    //文件名称
    header: Object.keys(USERS),
    data: a,
    filename: excelName.value || '导出表格'
  })
}


const logoutClick = async (row)=>{
  console.log(row)
  //拿到登录人的id
  let uid = store.getters.uid
  let sid = row.id

  if (row.admin > 1) {
    ElNotification({
      title: '注意',
      message: '不可设置超级管理员',
      type: 'warning',
    })
  } else if (row.logout === 0) {
    // 触发设置
    let res = await unsetL({
      uid,
      sid
    })
    if (res.error_code === 200) {
      ElNotification({
        title: '成功',
        message: res.msg,
        type: 'success',
      })

      await listFun(page.value, size.value)
    } else {
      ElNotification({
        title: '失败',
        message: res.msg,
        type: 'warning',
      })
    }


    console.log('row.logout === 1', res)
  } else if (row.logout === 1) {
    let res = await setL({
      uid,
      sid
    })
    if (res.error_code === 200) {
      ElNotification({
        title: '成功',
        message: res.msg,
        type: 'success',
      })

      await listFun(page.value, size.value)
    } else {
      ElNotification({
        title: '失败',
        message: res.msg,
        type: 'warning',
      })
    }
  }
}

const settingClick = async (row) => {
  console.log(row)
  //拿到登录人的id
  let uid = store.getters.uid
  let sid = row.id

  if (row.admin > 1) {
    ElNotification({
      title: '注意',
      message: '不可设置超级管理员',
      type: 'warning',
    })
  } else if (row.admin === 1) {
    // 触发设置
    let res = await unsetA({
      uid,
      sid
    })
    if (res.error_code === 200) {
      ElNotification({
        title: '成功',
        message: res.msg,
        type: 'success',
      })

      await listFun(page.value, size.value)
    } else {
      ElNotification({
        title: '失败',
        message: res.msg,
        type: 'warning',
      })
    }


    console.log('row.admin === 1', res)
  } else if (row.admin === 0) {
    let res = await setA({
      uid,
      sid
    })
    if (res.error_code === 200) {
      ElNotification({
        title: '成功',
        message: res.msg,
        type: 'success',
      })

      await listFun(page.value, size.value)
    } else {
      ElNotification({
        title: '失败',
        message: res.msg,
        type: 'warning',
      })
    }
  }
  //根据admin标识设置
  //admin <= 1 则可设置为0
  //admin > 1  则 不能设置（最高级别的管理员）
}


</script>
<style lang='scss' scoped>

.pagination {
  margin-top: 15px;
}

</style>
